//页面Gui
var SdsFormShow = {
    mrListId: $("#mrListId").val() == '' || $("#mrListId").val() == null ? 0 : $("#mrListId").val(),
    entityId: $("#entityId").val() == '' || $("#entityId").val() == null ? 0 : $("#entityId").val(),
    formCheckType: $("#formCheckType").val(),
    formData: {},			//表单项目数据
    layerIndex: -1,
    //全局变量 编辑值
    EditVal: new Array(),
    EditItem: new Array()
};
//当前窗口
const win = function () {
    if (window) {
        return window
    }
    return null
}();
//layer对象
const layer = function () {
    return win.layer
}();
$(function () {
    // 初始化表单内容
    SdsFormShow.InitViewData();
    // 初始化按钮状态
    SdsFormShow.InitMrButtons();
    // 加载各种事件
    SdsFormShow.LoadEvent();
});
/**
 * 初始化表单项目
 */
SdsFormShow.InitViewData = function () {
    layer.load();
    // 获取表单项目信息
    var ajax = new $ax("/sds/sdsqcformshow/getItemInfo/"+SdsFormShow.mrListId, function (data) {
        var itemInfo = data;
        for (var i = itemInfo.length - 1; i >= 0; i--) {
            var item = itemInfo[i];
            // 查询项目结果值并设置显隐属性
            var execVal = item.execResult;
            var editPower = item.editPower;
            var obj = $("#Row_"+item.id);
            obj.attr("editPower",editPower);
            if (editPower == 0) {
                obj.hide();
                // 判断子标题是否需要显示
                if (obj.prev().length===0)
                {
                    obj.parent().parent().prev().hide();
                }
            } else {
                obj.show();
                //判断子标题是否需要隐藏
                if (obj.prev().length===0)
                {
                    obj.parent().parent().prev().show();
                }
            }
            var itemType = $("#"+item.id).attr("itemType");
            switch (itemType) {
                case "CheckGroup": // 复选框
                    Common_CheckBoxToSDDic(item.id, itemType, execVal, 1);
                    break;
                case "RadioGroup": // 单选框
                    Common_RadioToSDDic(item.id, itemType, execVal, 2);
                    break;
                case "Combo": // 下拉框
                    Common_ComboToSDDic(item.id, itemType, execVal, 1);
                    break;
                default: //其他：文本、日期
                    Common_OtherToSDDic(item.id, itemType, execVal, 1);
                    break;
            }
        }
        layer.closeAll('loading');
    }, function () {
        layer.closeAll('loading');
    });
    ajax.setAsync();
    ajax.start();
};

function Common_GetItemInfo(itemId){
    var itemVal;
    var editPower = 0;
    var ajax = new $ax("/sds/sdsqcformshow/itemVal/" + itemId + "/" + SdsFormShow.mrListId, function (data) {
        itemVal = data.itemExec.itemResult?data.itemExec.itemResult : data.itemExec.initValue;
        editPower = data.editPower;
        if (editPower == 0) {
            $("#Row_"+itemId).hide();
        } else {
            $("#Row_"+itemId).show();
        }
        $("#Row_"+itemId).attr("editPower",editPower);

    }, function () {
    });
    ajax.setAsync();
    ajax.start();

    return itemVal;
}

/**
 * 下拉框字典
 */
function Common_ComboToSDDic() {
    var itemId = arguments[0];
    var DicType = arguments[1];
    var execVal = arguments[2];
    var columns = arguments[3] ? arguments[3] : 4;
    var dicArr = JSON.parse($("#Row_"+itemId).attr("dic"));

    $HUI.combobox("#" + itemId, {
        editable: false,
        defaultFilter: 4,
        allowNull: true,
        width: $("td input").outerWidth(),
        valueField: 'code',
        textField: 'desc',
        data: dicArr,
        // url: "/sds/sdsqcformshow/itemDics/" + itemId,
        onLoadSuccess: function () {
            var warnObj = $("#Warning_"+itemId);
            if (execVal != null && execVal != "") {
                $('#' + itemId).combobox('setValue', execVal);
            } else {
                if (warnObj.attr("btIsNeeded") == "1") {
                    warnObj.text("必填项不能为空!");
                }
            }
        },
        onSelect: function () {
            var itemVal = SdsFormShow.get(itemId, DicType);
            SdsFormShow.fireEvent(itemId, itemVal, DicType);
        },
        onUnselect: function () {
            var itemVal = SdsFormShow.get(itemId, DicType);
            SdsFormShow.fireEvent(itemId, itemVal, DicType);
        }
    });
}

/**
 * 多选字典
 */
function Common_CheckBoxToSDDic() {
    var itemId = arguments[0];
    var DicType = arguments[1];
    var execVal = arguments[2];
    var columns = arguments[3] ? arguments[3] : 4;

    var dicArr = JSON.parse($("#Row_"+itemId).attr("dic"));
    var len = dicArr.length;
    var count = parseInt(len / columns) + 1;
    var per = Math.round((1 / columns) * 100) + '%';  //每列所在百分比，等比分布
    //当前填写窗口的宽
    var divWidth = $("td div").outerWidth() * (1 / columns);
    var listHtml = ""
    for (var index = 0; index < count; index++) {
        var chklen = (((index + 1) * columns) < len) ? (index + 1) * columns : len;
        listHtml += "<div>";
        for (var dicIndex = index * columns; dicIndex < chklen; dicIndex++) {
            var dicSub = dicArr[dicIndex];
            var divWordCount = Math.floor(divWidth / 15)
            var divHeight = Math.ceil(dicSub.desc.length / divWordCount) * 25
            listHtml += " <div style='height:" + divHeight + "px;float:left;width:" + per + "'><input id=" + itemId + dicSub.id + " type='checkbox' class='hisui-checkbox' " + (dicSub.isDefault == 1 ? "checked='true'" : "") + ' label="' + dicSub.desc + '"  name=' + itemId + "  value=" + dicSub.code + "></div>";
        }
        listHtml += "</div>"
    }
    $('#' + itemId).html(listHtml);
    $.parser.parse('#' + itemId);  //解析checkbox

    // 设置项目结果
    if (execVal == null||execVal == "") {
        var warnObj = $("#Warning_"+itemId);
        if (warnObj.attr("btIsNeeded") == "1") {
            warnObj.text("必填项不能为空!");
        }
    } else {
        var resArr = execVal.split(',');
        for (var i=0,len=resArr.length;i<len;i++) {
            var option = resArr[i];
            if (option=="") continue;
            $('[name='+itemId+'][value='+option+']').checkbox('setValue', true);
        }
    }

    $("input[type='checkbox'][name='"+itemId+"']").checkbox({
        onCheckChange: function (){
            var itemVal = SdsFormShow.get(itemId, DicType);
            SdsFormShow.fireEvent(itemId, itemVal, DicType);
        }
    });
}

/**
 * 单选字典
 */
function Common_RadioToSDDic() {
    var itemId = arguments[0];
    var DicType = arguments[1];
    var execVal = arguments[2];
    var columns = arguments[3] ? arguments[3] : 4;

    var dicArr = JSON.parse($("#Row_"+itemId).attr("dic"));
    var len = dicArr.length;

    var count = parseInt(len / columns) + 1;
    var per = Math.round((1 / columns) * 100) + '%';  //每列所在百分比，等比分布
    //当前填写窗口的宽
    var divWidth = $("td div").outerWidth() * (1 / columns);
    var listHtml = ""
    for (var index = 0; index < count; index++) {
        var chklen = (((index + 1) * columns) < len) ? (index + 1) * columns : len;
        listHtml += "<div>";
        for (var dicIndex = index * columns; dicIndex < chklen; dicIndex++) {
            var dicSub = dicArr[dicIndex];
            var divWordCount = Math.floor(divWidth / 16)
            var divHeight = Math.ceil(dicSub.desc.length / divWordCount) * 25
            listHtml += "<div style='height:" + divHeight + "px;float:left;width:" + per + "'><input id=" + itemId + dicSub.id + " type='radio' class='hisui-radio' " + (dicSub.isDefault == 1 ? "checked='checked'" : "") + " label=" + dicSub.desc + " name=" + itemId + " value=" + dicSub.code + "></div>";
        }
        listHtml += "</div>"
    }
    $('#' + itemId).html(listHtml);
    $.parser.parse('#' + itemId);  //解析checkbox

    // 设置项目结果
    if (execVal == null||execVal == "") {
        var warnObj = $("#Warning_"+itemId);
        if (warnObj.attr("btIsNeeded") == "1") {
            warnObj.text("必填项不能为空!");
        }
    } else {
        $('[name='+itemId+'][value='+execVal+']').radio('setValue', true);
    }

    $("input[type='radio'][name="+itemId+"]").radio({
        onCheckChange: function (){
            var itemVal = SdsFormShow.get(itemId, DicType);
            SdsFormShow.fireEvent(itemId, itemVal, DicType);
        }
    });
}

/**
 * 其他：日期、时间、文本
 */
function Common_OtherToSDDic() {
    var itemId = arguments[0];
    var DicType = arguments[1];
    var execVal = arguments[2];
    var columns = arguments[3] ? arguments[3] : 4;

    switch (DicType) {
        case 'Date':
            $('#' + itemId).datebox({
                width: $("td input#"+itemId).outerWidth(),
                onSelect: function () {
                    var itemVal = $('#' + itemId).datebox("getValue");
                    SdsFormShow.fireEvent(itemId, itemVal, DicType);
                },
                onBlur: function (){
                    var itemVal = $('#' + itemId).datebox("getValue");
                    SdsFormShow.fireEvent(itemId, itemVal, DicType);
                }
            });
            break;
        case 'DateT':
            $('#' + itemId).datetimebox({
                width: $("td input#"+itemId).outerWidth(),
                onSelect: function () {
                    // 数据验证
                    var itemVal = $('#' + itemId).datetimebox("getValue");
                    SdsFormShow.fireEvent(itemId, itemVal, DicType);
                },
                onBlur: function (){
                    var itemVal = $('#' + itemId).datetimebox("getValue");
                    SdsFormShow.fireEvent(itemId, itemVal, DicType);
                }
            });
            break;
        default:
            $('#' + itemId).blur(function (){
                var itemVal = $('#' + itemId).val();
                SdsFormShow.fireEvent(itemId, itemVal, DicType);
            })
            break;
    };

    // 查询项目结果
    if (execVal == null||execVal == "") {
        var warnObj = $("#Warning_"+itemId);
        if (warnObj.attr("btIsNeeded") == "1") {
            warnObj.text("必填项不能为空!");
        }
    } else {
        switch (DicType) {
            case 'Date':
                $('#' + itemId).datebox("setValue", execVal);
                break;
            case 'DateT':
                $('#' + itemId).datetimebox("setValue", execVal);
                break;
            default:
                $('#' + itemId).val(execVal);
                break;
        }
    }
}

SdsFormShow.fireEvent = function (itemId, itemVal, DicType){
    //将编辑过的值存储起来，方便后面存储
    var iCodeIdx=SdsFormShow.EditItem.indexOf(itemId)
    if (iCodeIdx>-1){
        SdsFormShow.EditVal.splice(iCodeIdx,1,itemVal)
    }else {
        SdsFormShow.EditItem.push(itemId);
        SdsFormShow.EditVal.push(itemVal);
    }
    // 数据验证
    SdsFormShow.validItem(itemId, itemVal, DicType);
    // 前置条件
    SdsFormShow.ChangeRowEditor(itemId, $("#"+itemId).attr("itemCode"));
}

SdsFormShow.LoadEvent = function () {
    /*anchor-img*/
    $(".anchor-list li a").mouseover(function () {
        $(this).addClass("anchor-cur");
        $(this).popover({trigger: 'manual', placement: 'left', content: $(this).context.innerText});
        $(this).popover('show');
    });
    $(".anchor-list li a").mouseout(function () {
        $(this).removeClass("anchor-cur");
        $(this).popover('hide');
    });
    $('#btnSaveInfo').on('click',function() {
        var ret=SdsFormShow.validForm('Submit')
        if (ret) {
            SdsFormShow.saveReport('Submit')
        }
    });
    $('#btnSaveTmpInfo').on('click',function(){
        var ret=SdsFormShow.validTmpForm('Save')
        if (ret) {
            SdsFormShow.saveReport('Save');
        }
    });
    $('#btnCheckRep').on('click',function(){
        var CheckDesc=$('#btnCheckRep').linkbutton("options").text;
        //根据按钮描述，采取审核/取消审核操作
        if (CheckDesc=="取消审核"){
            var CheckCode="Submit"
        }else{
            var CheckCode="Check"
        }
        SdsFormShow.changeMrStat(CheckCode)
    });
    $('#btnUpInfo').on('click',function(){
        SdsFormShow.uploadReport('Up')
    });
    $('#btnOutSD').on('click',function(){
        SdsFormShow.changeMrStat('O')
    });
    $('#btnBackSD').on('click',function() {
        SdsFormShow.changeMrStat('Back');
    });
    $('#btnPrint').on('click',function() {
        window.print();
    });
};
SdsFormShow.InitMrButtons=function(){
    var ajax = new $ax("/sds/sdsqcformshow/mrState/" + SdsFormShow.mrListId, function (StatCode) {
        if (StatCode=="") StatCode="NotFilled";
        switch(StatCode) {
            case 'Submit':
                $('#btnSaveTmpInfo').hide();
                $('#btnSaveInfo').show();
                $('#btnCheckRep').linkbutton({text:'审 核'});
                // 如果医生直接上报，没有审核流程
                if (SdsFormShow.formCheckType == "Y") {
                    $('#btnCheckRep').hide();
                    $('#btnUpInfo').show();
                    $('#btnBackSD').hide();
                } else {
                    $('#btnCheckRep').show();
                    $('#btnUpInfo').hide();
                    $('#btnBackSD').show();
                }
                $('#btnOutSD').show();
                $('#btnPrint').show();
                break;
            case 'Save':
                $('#btnSaveTmpInfo').show();
                $('#btnSaveInfo').show();
                $('#btnCheckRep').hide();
                // 如果医生直接上报，没有审核流程
                if (SdsFormShow.formCheckType == "Y") {
                    $('#btnBackSD').hide();
                } else {
                    $('#btnBackSD').show();
                }
                $('#btnUpInfo').hide();
                $('#btnOutSD').show();
                $('#btnPrint').hide();
                break;
            case 'Back':
                $('#btnSaveTmpInfo').show();
                $('#btnSaveInfo').show();
                $('#btnCheckRep').hide();
                $('#btnBackSD').hide();
                $('#btnUpInfo').hide();
                $('#btnOutSD').show();
                $('#btnPrint').hide();
                break;
            case 'I':
                $('#btnSaveTmpInfo').show();
                $('#btnSaveInfo').show();
                $('#btnCheckRep').hide();
                $('#btnBackSD').hide();
                $('#btnUpInfo').hide();
                $('#btnOutSD').show();
                $('#btnPrint').hide();
                break;
            case 'O':
                $('#btnSaveTmpInfo').hide();
                $('#btnSaveInfo').hide();
                $('#btnCheckRep').hide();
                $('#btnBackSD').hide();
                $('#btnUpInfo').hide();
                $('#btnOutSD').hide();
                $('#btnPrint').hide();
                break;
            case 'Check':
                $('#btnSaveTmpInfo').hide();
                $('#btnSaveInfo').hide();
                $('#btnCheckRep').linkbutton({text:'取消审核'});
                // 如果医生直接上报，没有审核流程
                if (SdsFormShow.formCheckType == "Y") {
                    $('#btnCheckRep').hide();
                    $('#btnUpInfo').show();
                    $('#btnBackSD').hide();
                    $('#btnOutSD').show();
                } else {
                    $('#btnCheckRep').show();
                    $('#btnUpInfo').hide();
                    $('#btnBackSD').show();
                    $('#btnOutSD').hide();
                }
                $('#btnUpInfo').show();
                $('#btnPrint').show();
                break;
            case 'Up':
                $('#btnSaveTmpInfo').hide();
                $('#btnSaveInfo').hide();
                $('#btnCheckRep').hide();
                $('#btnBackSD').hide();
                $('#btnOutSD').hide();
                $('#btnUpInfo').hide();
                $('#btnPrint').show();
                break;
            default:
                break;
        }
    });
    ajax.start();
}
/**
 * 设置对话框中的数据
 *
 * @param key 数据的名称
 * @param val 数据的具体值
 * @param type 控件的类型
 */
SdsFormShow.set = function(key, type, value) {
    this.formData[key] = (typeof value == "undefined") ? this.get(key, type) : value;
    return this;
}

/**
 * 获取对话框中的数据
 *
 * @param key 数据的名称
 * @param type 控件的类型
 */
SdsFormShow.get = function(key, type) {
    var res = "";
    switch (type) {
        case "CheckGroup":
            $("input[type='checkbox'][name="+key+"]:checked").each(function (){
                //  选中复选框中的值
                res += $(this).val()+",";
            });
            res= res.substring(0,res.length - 1)
            break;
        case "RadioGroup":
            res =  $("input[type='radio'][name="+key+"]:checked").val();
            break;
        case "Combo":
            res =  $("#" + key).combobox("getValue");
            break;
        case 'Date':
            res = $('#' + key).datebox("getValue");
            break;
        case 'DateT':
            res = $('#' + key).datetimebox("getValue");
            break;
        default:
            res = $("#" + key).val();
            break;
    }
    return res;
}

/**
 * 关闭此对话框
 */
SdsFormShow.close = function() {
    parent.layer.close(parent.layer.getFrameIndex(window.name)); //先得到当前iframe层的索引,再执行关闭
}
/**
 * 清除数据
 */
SdsFormShow.clearData = function() {
    this.dictInfoData = {};
}
/**
 * 收集表单数据
 */
SdsFormShow.collectData = function () {
    // 收集已加载且已显示的项目数据
    $("#content tr[editPower=1] td:nth-child(2)").each(function () {
        var v = $(this).children()[0];
        SdsFormShow.set(v.id, v.attributes["itemType"].value);
    });
};
/**
 * 验证表单临时更改数据
 */
SdsFormShow.validTmpForm = function(aType){
    var validMsg="";
    if (SdsFormShow.EditItem.length==0) {
        $.messager.alert("错误提示", "没有编辑过的项目需要保存", 'info');
        return false;
    }
    // 检查所编辑的项目有无错误信息，有错则不进行保存
    for (var xind=0;xind<SdsFormShow.EditItem.length;xind++) {
        var xcode=SdsFormShow.EditItem[xind];
        var xNote=$('#Warning_'+xcode).text();
        if (xNote!=""&&xNote.indexOf("必填项不能为空")==-1){
            var itemDesc = $("#"+xcode).attr("title");
            validMsg+=itemDesc+":"+xNote+"<hr/>";
        }
    }
    if (validMsg) {
        $.messager.alert("错误提示",validMsg, 'error');
        return false;
    } else {
        return true;
    }
}
/**
 * 验证表单数据
 */
SdsFormShow.validForm = function(aType){
    var num = 0;
    var ErrorInfo=""
    $("#content tr[editPower=1]").each(function () {
        var v = $(this).children()[1].children[0];//数据列
        var w = $(this).children()[2].children[0];//信息列
        var ItemBTDesc = v.attributes["title"].value;// 项目描述
        var ItemValue = SdsFormShow.get(v.id, v.attributes["itemType"].value); //项目值
        var ItemBTIsNeeded = w.attributes["btIsNeeded"].value;//是否必填
        var WarningInfo = w.innerText;//提示信息
        if((aType=="Submit")&&(ItemValue=="")&&(ItemBTIsNeeded=="1")){
            num=num+1;
        }
        if (WarningInfo!=""&&WarningInfo.indexOf("必填项不能为空")==-1){
            ErrorInfo+=ItemBTDesc+":"+WarningInfo+"<hr/>"
        }
    });
    if (num>0) ErrorInfo+="该表单有"+num+"项必填项未填!<br/>";
    if(ErrorInfo!=""){
        $.messager.alert("错误提示",ErrorInfo,"error");
        return false;
    } else {
        return true;
    }
}

/**
 * 保存表单数据
 */
SdsFormShow.saveReport = function (sCode){
    var SDesc=(sCode=="Save"?"保存":sCode=="Submit"?"提交":1);
    $.messager.confirm("提示", "是否"+SDesc+"这份病例?", function (r) {
        if (r) {
            $.messager.progress({
                title: "提示",
                msg: '正在'+SDesc+'数据',
                text: '上传中....'
            });
            var Err = "";
            var MrListID = $("#mrListId").val();
            var ExecUser = $("#execUser").val();
            for (var xind=0;xind<SdsFormShow.EditItem.length;xind++) {
                var itemId	= SdsFormShow.EditItem[xind];
                var itemVal	= SdsFormShow.EditVal[xind];
                //提交信息
                var ajax = new $ax("/sds/sdsqcformshow/save", function (data) {
                    if (data.code == 500) {
                        var itemDesc = $("#"+itemId).attr("title");
                        Err += itemDesc + ":" + itemVal + "<br>";
                    }
                }, function (data) {
                    var itemDesc = $("#"+itemId).attr("title");
                    Err += itemDesc + ":" + itemVal + "<br>";
                });
                var params = {};
                params.mrListId = MrListID;
                params.execUser = ExecUser;
                params.itemId = itemId;
                params.itemVal = itemVal;
                ajax.setData(params);
                ajax.setAsync();
                ajax.start();
            }
            if (Err!="") {
                $.messager.progress("close");
                $.messager.alert("错误提示", "数据保存错误!键值明细:" + Err, 'info');
            }else{
                $.messager.progress("close");
                $.messager.popover({msg: '操作成功！',type:'success',timeout: 1000,style:{top:($(window).height()-50)/2+$(document).scrollTop(),left:($(window).width()-140)/2+$(document).scrollLeft()}});
                //更新状态
                var ax = new $ax("/sds/sdsqcformshow/changeMrStatus", function (data) {
                    SdsFormShow.InitMrButtons();
                    //操作成功后  清除编辑值记录
                    SdsFormShow.EditItem=[];
                    SdsFormShow.EditVal=[];
                }, function (data) {
                    $.messager.alert("错误提示", "状态更新错误!", 'info');
                });
                ax.set('mrListId', SdsFormShow.mrListId);
                ax.set('status', sCode);
                ax.set('execUser', $("#execUser").val())
                ax.set('reason', '');
                ax.set('resume', '');
                ax.start();
            }
        }
    });
}
/**
 * 更改表单状态
 */
SdsFormShow.changeMrStat = function (sCode){
    if (sCode=="") return;
    var SDesc=(sCode=="Check"?"审核":sCode=="Submit"?"取消审核":sCode=="Up"?"上传":sCode=="O"?"排除":sCode=="Back"?"退回":1)
    $.messager.confirm("提示", "是否"+SDesc+"这份病例?", function (r) {
        if (r) {
            if (sCode=="O") {
                //打开 弹出框
                var index = layer.open({
                    type: 2,
                    title: ['排除单病种【信息录入】'],
                    area: ['600px', '400px'],
                    zIndex: 19911102,//这是个大坑！！！！ 默认是19891014 远远大于量表下拉框的zIndex 导致下拉框的数据看不到！！！
                    content: "/sds/sdsqcformshow/excludereason?mrListId="+SdsFormShow.mrListId+"&entityId="+SdsFormShow.entityId+"&execUser="+$("#execUser").val(),
                    skin: 'layer-ext-hisui',
                    scrollbar: false,//为了禁止父页面滚动条滚动
                });
                this.layerIndex = index;
                //监听子页面的postMessage
                function receiveMessage(event) {
                    //取得子页面传回来的值
                    if (event.data == "close") {
                        // 如果传回close，关闭当前弹窗
                        layer.close(index);
                    }
                    if (event.data == "save") {
                        SdsFormShow.InitMrButtons();
                        setTimeout(function (){
                            layer.close(index);
                        },1000);
                    }
                }

                window.addEventListener('message', receiveMessage, false);
            } else if (sCode=="Back"){
                //退回报告需要填写退回原因
                $.messager.prompt("提示", "请输入退回原因：", function (r) {
                    if (r) {
                        //提交信息
                        var ajax = new $ax("/sds/sdsqcformshow/changeMrStatus", function (data) {
                            $.messager.popover({msg: SDesc+'操作成功！',type:'success',timeout: 1000,style:{top:($(window).height()-50)/2+$(document).scrollTop(),left:($(window).width()-140)/2+$(document).scrollLeft()}})
                            SdsFormShow.InitMrButtons();
                        }, function (data) {
                            $.messager.alert("错误提示", "状态更新错误!", 'info');
                        });
                        ajax.set('mrListId', SdsFormShow.mrListId);
                        ajax.set('status', sCode);
                        ajax.set('execUser', $("#execUser").val())
                        ajax.set('reason', '');
                        ajax.set('resume', r);
                        ajax.start();
                    } else {
                        $.messager.popover({msg:"您撤销了退回操作！",type:'info',style:{top:($(window).height()-50)/2+$(document).scrollTop(),left:($(window).width()-140)/2+$(document).scrollLeft()}});
                    }
                });
            } else {
                //提交信息
                var ajax = new $ax("/sds/sdsqcformshow/changeMrStatus", function (data) {
                    $.messager.popover({msg: SDesc+'操作成功！',type:'success',timeout: 1000,style:{top:($(window).height()-50)/2+$(document).scrollTop(),left:($(window).width()-140)/2+$(document).scrollLeft()}})
                    SdsFormShow.InitMrButtons();
                }, function (data) {
                    $.messager.alert("错误提示", "状态更新错误!", 'info');
                });
                ajax.set('mrListId', SdsFormShow.mrListId);
                ajax.set('status', sCode);
                ajax.set('execUser', $("#execUser").val())
                ajax.set('reason', '');
                ajax.set('resume', '');
                ajax.start();
            }
        }});
}
SdsFormShow.uploadReport = function (sCode){
    $.messager.progress({
        title: "提示",
        msg: '正在上传数据',
        text: '上传中....'
    });
    var ajax = new $ax("/sds/sdsqcformshow/upload/" + SdsFormShow.mrListId, function (UpRet) {
        $.messager.progress("close");
        if (UpRet.code==1) {
            $.messager.popover({msg: '上传成功！',type:'success',timeout: 1000,style:{top:($(window).height()-50)/2+$(document).scrollTop(),left:($(window).width()-140)/2+$(document).scrollLeft()}})
            //更新状态
            var ax = new $ax("/sds/sdsqcformshow/changeMrStatus", function (data) {
                $.messager.popover({msg: '状态更新成功！',type:'success',timeout: 1000,style:{top:($(window).height()-50)/2+$(document).scrollTop(),left:($(window).width()-140)/2+$(document).scrollLeft()}})
                SdsFormShow.InitMrButtons();
            }, function (data) {
                $.messager.alert("错误提示", "状态更新错误!", 'info');
            });
            ax.set('mrListId', SdsFormShow.mrListId);
            ax.set('status', sCode);
            ax.set('execUser', $("#execUser").val())
            ax.set('reason', '');
            ax.set('resume', '');
            ax.start();
        }else if(UpRet.message.indexOf('病案号重复')>0){
            //更新状态
            var ax = new $ax("/sds/sdsqcformshow/changeMrStatus", function (data) {
                $.messager.popover({msg: '已存在上传记录，状态更新成功！',type:'success',timeout: 1000,style:{top:($(window).height()-50)/2+$(document).scrollTop(),left:($(window).width()-140)/2+$(document).scrollLeft()}})
                SdsFormShow.InitMrButtons();
            }, function (data) {
                $.messager.alert("错误提示", "已存在上传记录，状态更新错误!", 'info');
            });
            ax.set('mrListId', SdsFormShow.mrListId);
            ax.set('status', sCode);
            ax.set('execUser', $("#execUser").val())
            ax.set('reason', '');
            ax.set('resume', '');
            ax.start();
        }else{
            $.messager.alert("错误提示", "表单上传失败!Error=" + UpRet.message, 'info');
        }
    }, function (data) {
        $.messager.alert("错误提示", "表单上传失败!", 'info');
    });
    ajax.setAsync();
    ajax.start();
}
/**
 * 表单项目校验
 * @param itemId 表单项目id
 * @param itemVal 表单项目结果
 * @param itemType 表单项目页面类型
 * @returns {string} 校验信息
 */
SdsFormShow.validItem = function(itemId, itemVal, itemType){
    //清空历史信息，准备显示最新的校验信息
    $("#Warning_" + itemId).text("");
    //如果当前项目值为空且是必填项目，则放弃该条校验
    if ((itemVal==""||itemVal==null)&&$("#Warning_" + itemId).attr("btIsNeeded") == "1") {
        $("#Warning_" + itemId).text("必填项不能为空!");
        return "";
    }
    var RuleItemIdArr = [];
    // 获取当前项目检验规则涉及到的项目，以便取值计算
    var ax = new $ax("/sds/sdsqcformshow/ruleLinkItem", function (data) {
        RuleItemIdArr = data;
    });
    ax.set("entityId", SdsFormShow.entityId);
    ax.set("formItemId", itemId);
    ax.start();

    var LinkItemObj = [];
    for (var i=0,l=RuleItemIdArr.length;i<l;i++){
        var RIdi=RuleItemIdArr[i];
        if (RIdi=="") continue;
        var RValuei=SdsFormShow.get(RIdi.itemId, itemType);
        LinkItemObj.push({'itemId':RIdi.itemId,'itemCode':RIdi.itemCode,'itemVal':RValuei});
    };

    var MsgArr = [];
    // 后台进行项目校验并返回错误信息
    var ajax = new $ax("/sds/sdsqcformshow/validMsg", function (data) {
        MsgArr = data;
    });
    var param = {};
    param.entityId = SdsFormShow.entityId;
    param.formItemId = itemId;
    param.formItemValue = itemVal;
    param.formItemType = itemType;
    param.formItemLink = JSON.stringify(LinkItemObj);
    ajax.setData(param);
    ajax.start();

    var msgStr = "";
    for (var j=0,l=MsgArr.length;j<l;j++){
        var Msg = MsgArr[j];
        var msgType = Msg.msgType;
        var msgContent = Msg.msgContent;
        if (msgType=='Stop') {
            $.messager.confirm("提示", msgContent+",是否退出并排除这份病例?", function (r) {
                if (r) {
                    SdsFormShow.changeMrStat('O');
                    return;
                }
            })
        } else {
            msgStr += msgContent + "\n";
        }
    }
    $("#Warning_" + itemId).text(msgStr);
}
/**
 * 项目间关联关系判断
 * @param itemId
 * @param itemCode
 * @constructor
 */
SdsFormShow.ChangeRowEditor=function(itemId, itemCode) {

    //根据该项目Code获取被关联项目的展现/隐藏属性
    var relativeItem = [];
    // 后台进行项目校验并返回错误信息
    var ajax = new $ax("/sds/sdsqcformshow/triggerLinkItem", function (data) {
        relativeItem = data;
    });
    var param = {};
    param.entityId = SdsFormShow.entityId;
    param.formItemId = itemId;
    param.formItemCode = itemCode;
    ajax.setData(param);
    ajax.start();

    // 如果没有关联此项的项目，退出；
    if (relativeItem.length == 0) {
        return;
    }
    for (var i=0,rl=relativeItem.length;i<rl;i++) {
        var relItem=relativeItem[i];
        if (relItem=="") continue;
        var linkItemArr = relItem.linkItem;
        for (var j=0,l=linkItemArr.length;j<l;j++) {
            var linkItem = linkItemArr[j];
            if (linkItem=="") continue;
            var linkId = linkItem.itemId;
            var linkVal = SdsFormShow.get(linkId, $("#"+linkId).attr("itemType"));
            linkItem['itemVal']=linkVal;
            linkItemArr[j] = linkItem;
        }
        relativeItem[i].linkItem = linkItemArr;
    };

    var MsgArr = [];
    // 后台进行项目校验并返回错误信息
    var ax = new $ax("/sds/sdsqcformshow/linkItemMsg", function (data) {
        MsgArr = data;
    });
    var param = {};
    param.entityId = SdsFormShow.entityId;
    param.formItemId = itemId;
    param.formItemLink = encodeURIComponent(JSON.stringify(relativeItem));
    ax.setData(param);
    ax.start();

    for(var m = 0,ml = MsgArr.length;m < ml;m++) {
        var item = MsgArr[m];
        var itemId = item.itemId;
        var showFlg = item.showFlg;
        var obj = $("#Row_"+item.itemId);
        if (obj.attr("editPower") != showFlg) {
            obj.attr("editPower",showFlg);
            if (showFlg == "0") {
                obj.hide();
                // 判断子标题是否需要显示
                if (obj.prev().length===0)
                {
                    obj.parent().parent().prev().hide();
                }
            } else {
                obj.show();
                // 判断子标题是否需要显示
                if (obj.prev().length===0)
                {
                    obj.parent().parent().prev().hide();
                }
            }
        }
    }
}